//使用摄像头捕获视频，将每一帧图像保存到文件

#include <stdio.h> //perror
//open
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <unistd.h>          //close
#include <sys/ioctl.h>       //ioctl
#include <stdlib.h>          //EXIT_FAILURE
#include <linux/videodev2.h> //V4L2
#include <string.h>          //memset
#include <sys/mman.h>        //mmap

#define BUF_NUM 3

struct userbuf{
    void* addr;
    size_t size;
};

struct userbuf buffers[BUF_NUM];

int main()
{
    //打开设备文件，需要读写权限
    int fd = open("/dev/video0", O_RDWR);
    if (fd < 0)
    {
        perror("open");
        return EXIT_FAILURE;
    }

    //获取设备能力(设备支持的操作)
    struct v4l2_capability cap;
    if (ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0)
    {
        perror("VIDIOC_QUERYCAP");
        return EXIT_FAILURE;
    }

    //设备是否支持视频捕获
    if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE))
    {
        fprintf(stderr, "The device does not handle single-planar video capture.\n");
        return EXIT_FAILURE;
    }

    //设备是否支持串流
    if (!(cap.capabilities & V4L2_CAP_STREAMING))
    {
        fprintf(stderr, "The device does not handle frame streaming.\n");
        return EXIT_FAILURE;
    }

    //获取默认图像格式
    struct v4l2_format format;
    format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    if (ioctl(fd, VIDIOC_G_FMT, &format) < 0)
    {
        perror("VIDIOC_G_FMT");
        return EXIT_FAILURE;
    }

    printf("default format: %c%c%c%c %dx%d\n",
           format.fmt.pix.pixelformat & 0xff,
           format.fmt.pix.pixelformat >> 8 & 0xff,
           format.fmt.pix.pixelformat >> 16 & 0xff,
           format.fmt.pix.pixelformat >> 24 & 0xff,
           format.fmt.pix.width,
           format.fmt.pix.height);

    //分配缓冲区（可以分配多个缓冲区多线程并行处理）
    struct v4l2_requestbuffers bufrequest;
    bufrequest.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    //缓冲区使用方式
    bufrequest.memory = V4L2_MEMORY_MMAP;
    //缓冲区个数
    bufrequest.count = BUF_NUM;

    if (ioctl(fd, VIDIOC_REQBUFS, &bufrequest) < 0)
    {
        perror("VIDIOC_REQBUFS");
        return EXIT_FAILURE;
    }

    int i;
    for (i = 0; i < BUF_NUM; i++)
    {
        //获取缓冲区信息
        struct v4l2_buffer bufferinfo;
        memset(&bufferinfo, 0, sizeof(bufferinfo));
        bufferinfo.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        bufferinfo.memory = V4L2_MEMORY_MMAP;
        bufferinfo.index = i;

        if (ioctl(fd, VIDIOC_QUERYBUF, &bufferinfo) < 0)
        {
            perror("VIDIOC_QUERYBUF");
            return EXIT_FAILURE;
        }

        //映射驱动缓冲区到用户空间
        buffers[i].addr = mmap(NULL,
                                bufferinfo.length,
                                PROT_READ | PROT_WRITE,
                                MAP_SHARED,
                                fd,
                                bufferinfo.m.offset);
        if (buffers[i].addr == MAP_FAILED)
        {
            perror("mmap");
            return EXIT_FAILURE;
        }

        buffers[i].size = bufferinfo.length;

        //启动串流前需要缓冲区先入队
        if (ioctl(fd, VIDIOC_QBUF, &bufferinfo) < 0)
        {
            perror("VIDIOC_QBUF1");
            return EXIT_FAILURE;
        }
    }
    
    //启动串流
    int type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    if (ioctl(fd, VIDIOC_STREAMON, &type) < 0)
    {
        perror("VIDIOC_STREAMON");
        return EXIT_FAILURE;
    }
    //帧数
    int frame = 0;

    while (1)
    {
        //出队前需要设置buffer的type，memory和reserve字段
        struct v4l2_buffer bufferinfo;
        memset(&bufferinfo, 0, sizeof(bufferinfo));
        bufferinfo.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        bufferinfo.memory = V4L2_MEMORY_MMAP;

        //等待一帧图像捕获完成后将缓冲区出队（默认阻塞）
        if (ioctl(fd, VIDIOC_DQBUF, &bufferinfo) < 0)
        {
            perror("VIDIOC_QBUF");
            break;
        }

        printf("dequeue frame %d, index = %d\n", frame, bufferinfo.index);

        //保存图像到文件
        char filename[20];

        sprintf(filename, "frame%03d.raw", frame++);

        int rawfile = open(filename, O_WRONLY | O_CREAT, 0660);
        if (rawfile < 0)
        {
            perror("open");
            break;
        }

        write(rawfile, buffers[bufferinfo.index].addr, bufferinfo.bytesused);
        close(rawfile);
        //缓冲区重新入队，清空标志位
        bufferinfo.flags = 0;

        if (ioctl(fd, VIDIOC_QBUF, &bufferinfo) < 0)
        {
            perror("VIDIOC_QBUF2");
            break;
        }
    }

    //停止串流
    if (ioctl(fd, VIDIOC_STREAMOFF, &type) < 0)
    {
        perror("VIDIOC_STREAMOFF");
        return EXIT_FAILURE;
    }

    close(fd);
    return EXIT_SUCCESS;
}
